<?php

namespace App\Http\Controllers\Admin;
use Config;
use Crypt;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Germey\Geetest\GeetestCaptcha;
use App\Models\AdminUsers;

class IndexController extends CommonController
{
	use GeetestCaptcha;
    public function index()
    {
    	return view('admin/index');
    }

    public function login(Request $request)
    {
    	$geetestChallenge = ['geetest_challenge' => 'geetest'];
    	//验证码错误提示
    	$geetestError = ['geetest' => Config::get('geetest.server_fail_alert')];
    	$result = $this->validate($request, $geetestChallenge, $geetestError);
      	if ($input = Input::all()) {
    		$adminUser = AdminUsers::first();
      		if($adminUser->user_name = $input['user_name'] && Crypt::decrypt($adminUser->password) == $input['password']){
      			session(['adminUser' => $adminUser]);
      			return redirect('admin/index');
      		}else{
      			return 'login error';
      		}
    	}else{
    		return view('admin/login');
    	}
    }

    public function logout()
    {
    	session(['adminUser' => null]);
    	return redirect('admin/login');
    }

    //修改管理员密码
    public function setPass()
    {
    	if($input = Input::all()){
    		$rules = [
    			'password' => 'required',
    			'new_password' => 'required|between:6,20|confirmed'
    		];
    		$message = [
    			'password.required' => '原密码不能为空',
    			'new_password.between' => '新密码必须为6-20位',
    			'new_password.confirmed' => '新密码与确认密码不一致',
    		];
    		$validator = Validator::make($input, $rules, $message);

    		if ($validator->passes()) {
    			// dd($adminUser);
    			$adminUser = AdminUsers::first();
    			$_password = Crypt::decrypt($adminUser->password);
    			if($input['password'] == $_password){
    				$adminUser->password = Crypt::encrypt($input['newPssword']);
    				
    				//$adminUser->update();
    			}else{
    				return back()->with('errors','原密码错误');
    			}
    		}else{
    			// dd($validator->errors());
    			return back()->withErrors($validator);
    		}
    	}else{
    		return view('admin/set_pass');
    	}
    }

    // public function crypt($value='')
    // {
    // 	$str = '123456';
    // 	if ($str) {
    // 		# code...
    // 	}
    // 	echo Crypt::encrypt($str);
    // }

}
